<template>
  <div class="home">
    <div class="home_header">
      <div class="productName">{{ productName }}</div>
      <Swipe :loanInfo="loanInfo" @loanChange="onLoanChange"/>
    </div>
    <div class="notice" v-if="contentText">
      <van-notice-bar
          background="#fff"
          left-icon="volume-o"
          scrollable
          :text="contentText"
          color="#7B7B7B"
      >
        <template #left-icon>
          <img style="height: 25px;width: 30px" src="../../assets/ic_gonggao.png">
        </template>
      </van-notice-bar>
    </div>
    <div class="loan_info">
      <!--       借款周期-->
      <div class="info_item" @click="selectDay" v-if="resourcesShow['loanTerm'] === 1">
        <div class="left">
          <img class="icon" src="../../assets/icon_jiekuanzhouqi.png">
          <span class="text">{{ $t('loan_term') }}</span>
        </div>
        <div class="right">
          <span class="text">{{ loanDay }} {{ $t('day') }}</span>
          <img class="icon" :style="{transform:!showSelectDay ? 'rotate(0deg)' : 'rotate(180deg)'}"
               src="../../assets/icon_down_arrow.png"/>
        </div>
      </div>

      <!--       日利率-->
      <div class="info_item" v-if="resourcesShow['loanInterest'] === 1 && listForm.interestType  === 1">
        <div class="left">
          <img class="icon" src="../../assets/icon_rililv.png">
          <span class="text">{{ $t('daily_rate') }}</span>
        </div>
        <div class="right">
          <span class="text">{{ listForm.loanInterest }}%</span>
        </div>
      </div>

      <!--       利息费用-->
      <div class="info_item" v-if="resourcesShow['interestFee'] === 1 ">
        <div class="left">
          <img class="icon" src="../../assets/ic_lixifeiyong.png">
          <span class="text">{{ $t('rateFee_detail') }}</span>
        </div>
        <div class="right">
          <span class="text"><span class="money_symbol">₫</span> {{ formatterMoney(listForm.interestFee) }}</span>
        </div>
      </div>
      <!--       还款金额-->
      <div class="info_item" v-if="resourcesShow['refundAmount'] === 1">
        <div class="left">
          <img class="icon" src="../../assets/icon_haikuan.png">
          <span class="text">{{ $t('repayment_amount') }}</span>
        </div>
        <div class="right">
          <span class="text">
            <span class="money_symbol">₫</span>
            {{ formatterMoney(listForm.refundAmount) }}</span>
        </div>
      </div>
      <van-action-sheet v-model:show="showSelectDay">
        <van-picker @confirm="onDaySelect" @cancel="showSelectDay = false"
                    :columns-field-names="{  text: 'name'}"
                    :default-index="20"
                    :columns="dayList"/>
      </van-action-sheet>
    </div>
    <div class="apply_now">
      <div style="display: flex;justify-content: center">
        <van-checkbox v-model="checked" icon-size="16px" shape="square"></van-checkbox>
        <span class="agreement">
            <span>{{ $t('agreement') }}</span>
          <a :href="privacyHref" class="active">{{ $t('privacy') }}</a>
         </span>
      </div>
      <button class="confirm" @click="applyNow">{{ $t('apply_now') }}</button>
    </div>
  </div>
</template>

<script>
import {ref, onMounted, reactive, toRefs, computed, watch, provide, nextTick} from 'vue'
import Swipe from '@/components/Swipe'
import {getPageProductCard, getNotice, userInfoVerify, uploadDeviceInfo,} from "@/api/home";
import {useI18n} from "vue-i18n";
import router from "@/router";
import {debounce, setResourcesShow, processNext, formatMoney} from '@/utils/tool'
import {useStore} from "vuex";
import MobileDetect from "mobile-detect";
import  {Toast} from 'vant'
export default {
  setup() {
    const {tm} = useI18n()
    const store = useStore()
    const current = ref(0);
    let checked = ref(true)
    let showSelectDay = ref(false)
    let loanDay = ref(0)
    let dayList = ref([])
    const loanTermList = ref([])
    let loanInfo = ref({})
    let listForm = ref({})
    let contentText = ref('')
    const resourcesShow = ref({})
    const productName = localStorage.getItem('productName')
    const privacyHref = computed(() => {
      const url = process.env.VUE_APP_AUTH
      return `${url}/${productName}/policy_sdkj.html`
    })
    const onChange = (index) => {
      current.value = index;
    };

    watch(() => listForm.value, (value) => {
      // 每次切换存储贷款信息
      localStorage.setItem('loanInfo', JSON.stringify(value))
    })
    const getCardList = async () => {
      const res = await getPageProductCard({productName: productName, userId: localStorage.getItem('userId') || ''})
      if (res.code === 1) {
        loanTermList.value = res.data.map(item => {
          item.array.sort((a, b) => {
            return a.loanTerm - b.loanTerm
          })
          return item
        })
        // 默认最大天数
        loanDay.value = loanTermList.value[loanTermList.value.length - 1].loanTerm
        dayList.value = loanTermList.value.map(item => {
          item = {
            name: item.loanTerm + tm('day'),
            loanTerm: item.loanTerm,
          }
          return item
        })
        loanInfo.value = loanTermList.value[loanTermList.value.length - 1]
      }
      // 清除loading
      store.dispatch('changeLoading', false)
    }

    //选择天数
    const selectDay = () => {
      showSelectDay.value = true
    }
    const onDaySelect = (value) => {
      loanDay.value = value.loanTerm
      showSelectDay.value = false
      loanInfo.value = loanTermList.value.filter(item => item.loanTerm === value.loanTerm)[0]
    }
    // 子组件值
    const onLoanChange = (val) => {
      listForm.value = val
    }
    // 获取通知列表
    const fetchNotice = async () => {
      const res = await getNotice()
      if (res.code === 1) {
        const list = res.data.list
        let str = ''
        list.forEach(i => {
          str += i.content
        })
        contentText.value = str
      }
    }
    const send_fill_Info = debounce(async () => {
      const res = await userInfoVerify()
      if (res.code === 1) {
        // 校验用户填写状态与 菜单显示隐藏
        localStorage.setItem('userInfoVerify', JSON.stringify(res.data))
        let data = JSON.parse(localStorage.getItem('userInfoVerify'))
        const {
          ongoingOrder,
          pendingRepayment,
        } = data
        if (ongoingOrder || pendingRepayment) {
          Toast({
            message: tm('hint_apply_later')
          })
          return
        }
        /**
         * null 占位  埋点当前点击去的路由
         */
        processNext(null, '/home/index')
      }
    })
    const applyNow = () => {
      if (localStorage.getItem('userId')) {
        if (!checked.value) {
          Toast({
            message: tm('hint_check_agreement')
          })
          return
        } else {
          localStorage.setItem('isUserPrivacy', true)
        }
        // 不可借
        if (!listForm.value.canBorrow) {
          Toast({
            message: tm('hint_insufficient_score')
          })
        } else {
          send_fill_Info()
        }
      } else {
        router.push('/login')
      }
    }
    // 菜单显示隐藏
    const getResourcesShow = async () => {
      resourcesShow.value = await setResourcesShow(9)
    }
    // 格式化金额
    const formatterMoney = (value) => {
      if (value) {
        return formatMoney(value, 0, "", '.')
      } else {
        return value
      }
    }
    // 上传设备信息
    const saveDeviceInfo = async () => {
      const md = new MobileDetect(navigator.userAgent)
      await uploadDeviceInfo({
        is_simulator: 1,
        deviceInfo: md.phone() || '',
        osType: md.os() || '',
        mobileModel: md.mobile()
      })
    }
    getResourcesShow()
    getCardList()
    fetchNotice()
    onMounted(() => {
      if (localStorage.getItem('isUserPrivacy') === 'true') {
        checked.value = true
      }
      if (localStorage.getItem('token')) {
        saveDeviceInfo()
      }
    })
    return {
      loanDay,
      contentText,
      showSelectDay,
      onDaySelect,
      current,
      onChange,
      checked,
      selectDay,
      dayList,
      loanInfo,
      resourcesShow,
      listForm,
      applyNow,
      privacyHref,
      productName,
      formatterMoney,
      onLoanChange
    };
  },
  components: {
    Swipe
  }
}
</script>

<style lang="less" scoped>
.home {
  width: 100%;
  background-color: #F7F7F7;

  .home_header {
    position: relative;
    width: 100%;
    height: 225px;
    text-align: center;
    z-index: 1;
    overflow: hidden;
    background-color: #ffffff;

    .productName {
      position: absolute;
      top: 15px;
      font-size: 20px;
      color: #FFFFFF;
      left: 20px;
    }
  }

  .home_header:after {
    width: 140%;
    height: 150px;
    position: absolute;
    left: -20%;
    top: 0;
    content: '';
    border-radius: 0 0 50% 50%;
    z-index: -1;
    background-color: #FF5A50;
  }

  .notice {
    margin-top: 10px;
    background-color: #ffffff;
  }

  .loan_info {
    margin-top: 10px;

    .info_item {
      background-color: #ffffff;
      line-height: 50px;
      padding: 0 10px;
      display: flex;
      justify-content: space-between;

      .left {
        display: flex;
        align-items: center;

        .icon {
          height: 30px;
          width: 30px;
          margin-right: 10px;
        }

        .text {
          font-size: 14px;
          font-weight: 600;
          color: #333333;
        }
      }

      .right {
        display: flex;
        align-items: center;

        .text {
          font-size: 14px;
          font-weight: 600;
          color: #FF6A42;
          display: flex;
          align-items: center;
        }

        .icon {
          display: flex;
          align-items: center;
          margin-left: 10px;
          height: 10px;
          width: 14px;
          transition-duration: .3s;

        }
      }
    }

    .info_item::after {
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      content: "";
      width: 80%;
      border-bottom: solid 1px #F7F7F7;
    }
  }

  .apply_now {
    margin-top: 30px;
    text-align: center;

    .agreement {
      font-size: 10px;
      color: #7B7B7B;
      margin-left: 10px;

      .active {

        color: #FF6A42;
      }
    }

    .confirm {
      margin-top: 15px;
      margin-bottom: 15px;
      width: 250px;
      height: 38px;
      color: #ffffff;
      border: none;
      font-size: 18px;
      background: linear-gradient(-45deg, #FF5252, #FF8C3C);
      box-shadow: 0px 4px 10px 0px rgba(255, 92, 78, 0.52);
      border-radius: 29px;
    }
  }
}
</style>
